package ua.com.softway.mail;

import java.util.List;

import javax.mail.AuthenticationFailedException;
import javax.mail.MessagingException;

import org.apache.log4j.Logger;


class SendMailThread extends Thread {
    private final static Logger log = Logger.getLogger(SendMailThread.class);

    private final MailQueue mailQueue;
    private final MailerConfig mailConfig;

    public SendMailThread(MailQueue mailQueue, MailerConfig mailConfig) {
        this.mailQueue = mailQueue;
        this.mailConfig = mailConfig;

        setName("SendMailThread");
    }

    public void run() {
        while (true) {
            List<GeneratedMessage> msgs;

            try {
                msgs = mailQueue.take();
            } catch (InterruptedException e) {
                return;
            }
            
            for (GeneratedMessage msg : msgs) {
                MailAccount account = null;
                
                try {
                    boolean sent = false;
                    
                    while (!sent) {
                        account = mailConfig.getAccount(msg);
                        
                        if (account == null) {
                            log.error("No available mail account to send email");
                            msg.state = GeneratedMessage.NoMailAccount;
                            break;
                        } else
                            sent = account.send(msg);
                    }
                } catch (AuthenticationFailedException e) {
                    break;
                } catch ( MessagingException e ) {
                    msg.state = GeneratedMessage.Error;
                    log.error("Can't send mailMessage via account " + account + ", " + e);
                } catch (Throwable t) {
                    msg.state = GeneratedMessage.Error;
                    log.error("Can't send mailMessage: ", t);
                }
            }
        }
    }
}
